<?php
/**
 * Created by PhpStorm.
 * User: songdewei
 * Date: 2017/10/11
 * Time: 下午3:38
 */

namespace App\WeChat\WxApi;


use App\WeChat\Models\SnsUserinfo;
use GuzzleHttp\Client;
use Intervention\Image\Facades\Image;

class WxJsApi extends WxApi
{
    /**
     * @param $code
     * @return SnsUserinfo
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Exception
     */
    public static function getUserinfoWithCode($code)
    {

        $uri = self::createOauthUrlForOpenid($code);
        $client = new Client();
        $response = $client->get($uri);
        $data = json_decode($response->getBody(), true);
        if (isset($data['openid']) && isset($data['access_token'])) {
            $uri = "https://api.weixin.qq.com/sns/userinfo?access_token=$data[access_token]&openid=$data[openid]&lang=zh_CN";
            $response = $client->get($uri);
            $data = json_decode($response->getBody(), true);
            if (isset($data['openid'])) {
                return new SnsUserinfo($data);
            } else {
                throw new \Exception($data['errmsg'], $data['errcode']);
            }
        }else {
            throw new \Exception($data['errmsg'], $data['errcode']);
        }
    }

    /**
     * 构造获取code的url连接
     * @param $redirectUrl
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function createOauthUrlForCode($redirectUrl)
    {
        $api = new static();
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$api->appid;
        $url.= '&redirect_uri='.urlencode($redirectUrl).'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
        return $url;
    }

    /**
     * 构造获取open和access_toke的url地址
     * @param $code
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function createOauthUrlForOpenid($code)
    {
        $api = new static();
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$api->appid;
        $url.= '&secret='.$api->secret.'&code='.$code.'&grant_type=authorization_code';
        return $url;
    }

    public static function syncHeadImg($uid, $uri){
        ignore_user_abort(true);
        $client = new Client();
        $response = $client->get($uri);
        $handle = Image::make($response->getBody());
        $avatarPath = storage_public_path('avatar/'.$uid);
        @mkdir($avatarPath, 0777, true);
        $handle->resize(300, 300)->save($avatarPath.'/big.png');
        $handle->resize(150, 150)->save($avatarPath.'/middle.png');
        $handle->resize(50, 50)->save($avatarPath.'/small.png');
        return true;
    }
}
